//========================================================================
// *作者：海盗猫  主页：ilplay.com
// *脚本：DrawDeployAssembly
// *描述：
// *?2021 MYJL . All rights reserved.
//* ======================================================================
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.IO;
using HDMCode.ExcelEditor;
using System.Diagnostics;
using System.Text;
using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace HDMCode.Hotfix
{
    [UnityEditor.InitializeOnLoad]
    public class DrawDeployAssembly
    {
        private static readonly GUIContent m_OpenExETool;
        private static OnDataReceived m_OnDataReceivedHandler;
        private delegate void OnDataReceived(string message);
        private static readonly string m_LubanPath = $"{System.Environment.CurrentDirectory}/luban/";
        private static readonly string m_LubanDatePath = $"{m_LubanPath}/MiniTemplate/Datas";
        private static readonly string m_SettingPath = $"{HDMFrameExcelPage.PackedAssetsPath}/ExeclSetting.asset";
        public static readonly string LubanConfigPath = $"{m_LubanPath}MiniTemplate/Defines/builtin.xml";
        private static DrawExcelSetting m_DrawExeclSetting { get; set; }

        static DrawDeployAssembly()
        {
            m_OpenExETool = EditorGUIUtility.TrTextContentWithIcon(" 映射配置表", "用于配置表的映射处理", "SceneViewRGB");
            UnityEditorToolbar.LeftToolbarGUI.Add(OnRightToolbarGUI);
        }

        private static void OnRightToolbarGUI()
        {
            GUILayout.Space(5);
            if (GUILayout.Button(m_OpenExETool, EditorStyles.foldoutHeader, GUILayout.Width(100)))
            {
                m_DrawExeclSetting = AssetDatabase.LoadAssetAtPath<DrawExcelSetting>(m_SettingPath);
                var filtrateList = FrameEditor.HDMEditorFileIO.GetSyncAllFile(m_DrawExeclSetting.ExeclPath);
                if (!Directory.Exists(m_DrawExeclSetting.ExeclPath))
                    UnityEngine.Debug.LogError($"未检测到配置表文件夹: {m_DrawExeclSetting.ExeclPath}");

                if (Directory.Exists(m_LubanDatePath))
                {
                    Directory.Delete(m_LubanDatePath,true);
                    Directory.CreateDirectory(m_LubanDatePath);
                }
                else
                {
                    EditorUtility.DisplayDialog("提示","此功能需安装Luban","好的");
                    return;
                }

                foreach (var item in filtrateList)
                {
                    var head = item.fileName.ToCharArray()[0];
                    if (head.ToString()=="_")
                        File.Copy(item.assetsPath, $"{m_LubanDatePath}/{item.fileName}");
                    else
                        File.Copy(item.assetsPath, $"{m_LubanDatePath}/#{item.fileName}");
                }
                
                File.Copy(HDMFrameExcelPage.PackedProjectLubanPath, $"{m_LubanDatePath}/__tables__.xlsx");
                ReadBat();
                AssetDatabase.Refresh();
            }
            GUILayout.Box("", GUIStyle.none, GUILayout.ExpandWidth(true));
        }

        public static void ReadBat()
        {
            try
            {
                Thread thread = new Thread(new ThreadStart(() =>
                {
                    m_OnDataReceivedHandler += (result) =>{UnityEngine.Debug.Log(result);};
                    StringBuilder command = new StringBuilder();
                    command.Append($"dotnet {m_LubanPath}/Tools/Luban/Luban.dll ^" +
                                   $"-t client ^" +
                                   $"-d json ^" +
                                   $"-c cs-simple-json ^" +
                                   $"--conf {m_LubanPath}/MiniTemplate/luban.conf ^" +
                                   $"-x outputCodeDir={m_DrawExeclSetting.OutPutClientPath}/Client/Script ^" +
                                   $"-x outputDataDir={m_DrawExeclSetting.OutPutClientPath}/Client/Json");
                    Execute(command.ToString());
                    
                    command.Clear();
                    command.Append($"dotnet {m_LubanPath}/Tools/Luban/Luban.dll ^" +
                                   $"-t server ^" +
                                   $"-d json ^" +
                                   $"-c cs-simple-json ^" +
                                   $"--conf {m_LubanPath}/MiniTemplate/luban.conf ^" +
                                   $"-x outputCodeDir={m_DrawExeclSetting.OutPutServerPath}/Server/Script ^" +
                                   $"-x outputDataDir={m_DrawExeclSetting.OutPutServerPath}/Server/Json");
                    Execute(command.ToString());
                }));
                thread.Start();
                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError("映射异常错误："+e.Message);
            }

        }


        /// <summary>
        /// 打开EXE工具
        /// </summary>
        [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
        public static extern int ShellExecute(IntPtr hwnd, string lpszOp, string lpszFile, string lpszParams, string lpszDir, int FsShowCmd);
        public static void OpenEXETool(string Path, string IDEPath="")
        {
            if (EditorApplication.isPlaying)
                EditorApplication.isPlaying = false;

            if (!string.IsNullOrEmpty(IDEPath))
                ShellExecute(IntPtr.Zero, "open", $"" + IDEPath, "", "", 1);
            else
                ShellExecute(IntPtr.Zero , "open", Path, "", "", 1);
        }
        
        private static void Execute(string command)
        {
            command = "/c chcp 437&&" + command.Trim().TrimEnd('&') + "&exit";
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = command;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;

            StringBuilder str = new StringBuilder();
            str.AppendLine("海盗猫配置表映射日志：\n");
            process.OutputDataReceived += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(e.Data))
                    str.AppendLine(e.Data) ;
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(e.Data))
                    str.AppendLine(e.Data) ;
            };
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
            process.Close();
            m_OnDataReceivedHandler?.Invoke(str.ToString());
        }
    }
}

#endif